import { Injectable } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'

import { UserDto, EditUserDto } from './dto'
import { WxUser, UserDocument } from '@libs/db/schemas/user.schema'

@Injectable()
export class ExampleService {
  constructor(@InjectModel(WxUser.name) private WxUserModel: Model<UserDocument>) {}

  async getAllData(): Promise<WxUser[]> {
    return await this.WxUserModel.find().exec()
  }

  async createDate(wxUser: UserDto) {
    const user = await this.WxUserModel.create(wxUser)
    return user
  }

  async daleteDate(username: string) {
    // const res = await this.WxUserModel.remove({ username }); // 全部符合记录
    const query = { username }
    const res = await this.WxUserModel.findOneAndRemove(query) // 一条
    return res
  }

  async updateDate(id: string, wxUser: EditUserDto) {
    const query = { _id: id }
    const update = {
      $set: wxUser,
    }
    const res = await this.WxUserModel.findOneAndUpdate(query, update, {
      new: true,
    })
    return res
  }

  async findDate(username: string) {
    const regex = new RegExp(username, 'ig')
    const query = { username: { $regex: regex } }
    // return await this.WxUserModel.find({ name }).exec();
    return await this.WxUserModel.find(query).exec()
  }
}
